package com.yw.swagger.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.yw.swagger.customNote.qw;
import com.yw.swagger.tool.AjaxResult;
import com.yw.swagger.tool.Global;
import com.yw.swagger.tool.ServerConfig;
import com.yw.swagger.tool.Utils.FileUploadUtils;
import com.yw.swagger.tool.Utils.FileUtils;
import com.yw.swagger.tool.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: Abeiv
 * @Description: 系统通用操作
 * @Date: 2019/10/25 13:27
 */
@Api(tags = "系统通用接口")
@Controller()
@RequestMapping("/system")
public class SystemController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(SystemController.class);

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

//    /**
//     * 通用上传请求
//     */
//    @qw
//    @ApiOperation(value = "文件上传",notes = "文件上传")
//    @ApiImplicitParam(name="author",value="权限码",required = true)
//    @PostMapping("/upload")
//    @ResponseBody
//    public AjaxResult uploadFile(MultipartFile file) throws Exception
//    {
//        try
//        {
//            // 上传文件路径
//            String filePath = Global.getUploadPath();
//            // 上传并返回新文件名称
//            String fileName = FileUploadUtils.upload(filePath, file);
//            String url = ServerConfig.getUrl() + fileName;
//            AjaxResult ajax = AjaxResult.success();
//            ajax.put("fileName", fileName);
//            ajax.put("url", url);
//            return ajax;
//        }
//        catch (Exception e)
//        {
//            return AjaxResult.error(e.getMessage());
//        }
//    }






    /**
     * 通用上传请求
     */
    @qw
    @ApiOperation(value = "文件上传",notes = "文件上传")
    @ApiImplicitParam(name="author",value="权限码",required = true)
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile[]file) throws Exception{
        try
        {
            AjaxResult ajax = AjaxResult.success();
            String fileName="";
            String url="";
            for (MultipartFile f: file){
                // 上传文件路径
                String filePath = Global.getUploadPath();
                // 上传并返回新文件名称
               String name= FileUploadUtils.upload(filePath, f);
                if(fileName.equals("")){
                    fileName = name;
                }else {
                    fileName=fileName+","+name;
                }
                if (url.equals("")){
                    url= ServerConfig.getUrl() + name;
                }else {
                    url=url+","+ServerConfig.getUrl()+name;
                }
                ajax.put("fileName", fileName);
                ajax.put("url", url);
            }
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 通用下载
     */
    @qw
    @ApiOperation(value = "文件下载",notes = "文件下载")
    @ApiImplicitParams({
            @ApiImplicitParam(name="author",value="权限码",required = true),
            @ApiImplicitParam(value = "文件名", name = "fileName",required = true),
            @ApiImplicitParam(value = "是否删除源文件", name = "delete")
    })
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
//            if (!FileUtils.isValidFilename(fileName))
//            {
//                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
//            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = Global.getUploadPath() + "/"+fileName;
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath,fileName, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }



    /**
     * 验证码生成
     */
    @qw
    @ApiOperation(value = "验证码生成",notes = "验证码生成")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "验证码类型 （char math）", name = "type",required = true),
    })
    @GetMapping(value = "/captchaImage")
    public ModelAndView captchaImage(HttpServletRequest request, HttpServletResponse response)
    {
        ServletOutputStream out = null;
        try
        {
            HttpSession session = request.getSession();
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            response.setContentType("image/jpeg");

            String type = request.getParameter("type");
            String capStr = null;
            String code = null;
            BufferedImage bi = null;
            if ("math".equals(type))
            {
                String capText = captchaProducerMath.createText();
                capStr = capText.substring(0, capText.lastIndexOf("@"));
                code = capText.substring(capText.lastIndexOf("@") + 1);
                bi = captchaProducerMath.createImage(capStr);
            }
            else if ("char".equals(type))
            {
                capStr = code = captchaProducer.createText();
                bi = captchaProducer.createImage(capStr);
            }
            session.setAttribute(Constants.KAPTCHA_SESSION_KEY, code);
            out = response.getOutputStream();
            ImageIO.write(bi, "jpg", out);
            out.flush();

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                if (out != null)
                {
                    out.close();
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return null;
    }


    @qw
    @ApiOperation(notes = "获取一周的日期",value = "获取一周的日期")
    @GetMapping("/getWeekDay")
    @ResponseBody
    public AjaxResult getWeekDay(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        // 今天是一周中的第几天
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK );

        if (c.getFirstDayOfWeek() == Calendar.SUNDAY) {
            c.add(Calendar.DAY_OF_MONTH, 1);
        }
        // 计算一周开始的日期
        c.add(Calendar.DAY_OF_MONTH, -dayOfWeek);
        Map<String, List> data = new HashMap<>();
        List weekd = new ArrayList();
        for (int i=1;i<=7;i++) {
            c.add(Calendar.DAY_OF_MONTH, 1);
            System.out.println(sdf.format(c.getTime()));
            weekd.add(sdf.format(c.getTime()));
        }
        List l = new ArrayList();
        l.add("周一");
        l.add("周二");
        l.add("周三");
        l.add("周四");
        l.add("周五");
        l.add("周六");
        l.add("周日");
        data.put("weekDay",l);
        data.put("day",weekd);
        return AjaxResult.success(weekd);
    }


}
